﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Lib.Common;
using SDT.Model;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 13/06/2011
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class ProductCategoryController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /ProductCategory/
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("productCategory.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("productCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("productCategory.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("productCategory.pageSize", "PageSize", 20).ToString());
                    byte typeID = byte.Parse(UserState.getUserStateFromRequest("productCategory.TypeID", "TypeID", 0).ToString());
                    string strPub = UserState.getUserStateFromRequest("productCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var categories = eDataContext.ProductCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => typeID > 0 ? (c.TypeID.HasValue && c.TypeID.Value == typeID) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);
                    List<SelectListItem> listT = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                     Text = t.Name,
                                                     Value = t.ID.ToString()
                                                }).ToList();
                    if (typeID > 0)
                        listT.SingleOrDefault(t => t.Value == typeID.ToString()).Selected = true;

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new ProductCategoryViewModels
                    {
                        Categories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ListProductType = listT,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /ProductCategory/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                    ProductCategory proCat = eDataContext.ProductCategories.Where(c => c.ID == id).SingleOrDefault();
                    List<SelectListItem> listT = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                    Text = t.Name,
                                                    Value = t.ID.ToString()
                                                }).ToList();
                    List<TreeNodeItem> listTree = eDataContext.ProductCategories
                                                    .Where(c => c.ID != proCat.ID)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, proCat.ParentID);
                    
                    if (proCat.TypeID.HasValue)
                        listT.SingleOrDefault(t => t.Value == proCat.TypeID.Value.ToString()).Selected = true;

                    return View(new ProductCategoryEditModels
                    {
                        ListParentCategories = categories,
                        Category = proCat,
                        ListProductType = listT
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /ProductCategory/Create
        public ActionResult Create()
        {
            try
            {
                    List<SelectListItem> listT = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                    Text = t.Name,
                                                    Value = t.ID.ToString()
                                                }).ToList();
                    List<TreeNodeItem> listTree = eDataContext.ProductCategories
                                                    .Select(c => new TreeNodeItem()
                                                     {
                                                         Value = c.ID,
                                                         Text = c.Name,
                                                         ParentID = c.ParentID
                                                     }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new ProductCategoryInputModels
                    {
                        ListCategories = categories,
                        ListProductType = listT
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /ProductCategory/Create

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(ProductCategoryInputModels m)
        {
            try
            {
                    m.Category.AddBy = UserManager.GetUserId();
                    m.Category.ParentID = Request["ParentID"] != null && Request["ParentID"] != string.Empty ? Utils.ParseInt(Request["ParentID"]) : (int?)null;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    m.Category.AddDate = DateTime.Now;
                    m.Category.ModifyDate = DateTime.Now;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    eDataContext.ProductCategories.InsertOnSubmit(m.Category);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /ProductCategory/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    ProductCategory proCat = eDataContext.ProductCategories.Where(c => c.ID == id).SingleOrDefault();
                    List<SelectListItem> listT = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                    Text = t.Name,
                                                    Value = t.ID.ToString()
                                                }).ToList();
                    List<TreeNodeItem> listTree = eDataContext.ProductCategories
                                                    .Where(c => c.ID != proCat.ID)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, proCat.ParentID);
                    if (proCat.TypeID.HasValue)
                        listT.SingleOrDefault(t => t.Value == proCat.TypeID.Value.ToString()).Selected = true;

                    return View(new ProductCategoryEditModels
                    {
                        ListParentCategories = categories,
                        Category = proCat,
                        ListProductType = listT
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /ProductCategory/Edit/5
        
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, ProductCategoryInputModels m)
        {
            try
            {
                    m.Category = eDataContext.ProductCategories.Where(c => c.ID == id).SingleOrDefault();
                    UpdateModel(m);
                    m.Category.ParentID =Request["ParentID"]!=null && Request["ParentID"]!=string.Empty? Utils.ParseInt(Request["ParentID"]):(int?)null;
                    m.Category.ActiveYN = Request["rdActiveYN"].ToLower() == "true" ? true : false;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    m.Category.AddDate = DateTime.Now;
                    m.Category.ModifyDate = DateTime.Now;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    int nChildren = eDataContext.ProductCategories.Where(i => i.ParentID.HasValue && i.ParentID.Value == id).Count();
                    if (nChildren > 0)
                        throw new Exception("Chuyên mục bạn xoá là chuyên mục cha. Nên bạn không thể xoá được. Hãy xoá chuyên mục con trước.");

                    int nItems = eDataContext.Products.Where(p => p.CatID == id).Count();
                    if (nItems > 0)
                        throw new Exception("Chuyên mục bạn xoá có chứa tin rao vặt. Bạn hãy xoá tin rao vặt trước rồi hãy xoá chuyên mục");

                    ProductCategory proCat = eDataContext.ProductCategories.SingleOrDefault(e => e.ID == id);
                    
                    return View(proCat);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    ProductCategory item = eDataContext.ProductCategories.SingleOrDefault(e => e.ID == id);
                    if (item != null)
                    {
                        eDataContext.ProductCategories.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
